package com.cqc.zhbjcqc.fragment.frag2.fragnews;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.cqc.zhbjcqc.R;
import com.cqc.zhbjcqc.activity.NewsDetailActivity;
import com.cqc.zhbjcqc.adapter.FragNewsItemAdapter;
import com.cqc.zhbjcqc.adapter.FragNewsItemViewPager;
import com.cqc.zhbjcqc.bean.FragNewsItemBean;
import com.cqc.zhbjcqc.fragment.BaseFragment;
import com.cqc.zhbjcqc.net.MainRequest;
import com.cqc.zhbjcqc.net.NetUrl;
import com.cqc.zhbjcqc.utils.GsonUtil;
import com.cqc.zhbjcqc.utils.LogUtil;
import com.cqc.zhbjcqc.utils.ToastUtil;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by cui on 2016/9/28.
 */

public class FragNewsItem extends BaseFragment {

    private static final String TAG = "FragNewsItem";
    private View rootView;
    private PullToRefreshListView ptf;
    private String url;
    private ListView listView;
    private List<FragNewsItemBean.DataBean.NewsBean> list = new ArrayList<>();
    private List<FragNewsItemBean.DataBean.TopnewsBean> topnewsList;
    private List<String> topImagesList = new ArrayList<>();
    private List<String> topTitleList = new ArrayList<>();
    private List<TextView> dotsList = new ArrayList<>();
    private String moreUrl;
    private FragNewsItemAdapter adapter;
    private ViewPager viewPager;
    private TextView tv_desc;
    private TextView tv_ratio;
    private LinearLayout ll_dots;

    public FragNewsItem(String url) {
        this.url = url;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.frag_news_item, container, false);
        initPtf();
        initListView();
        return rootView;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        requestData(url);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                LogUtil.d(TAG,"list.get(position).getUrl()="+list.get(position).getUrl());
                Intent intent = new Intent(context, NewsDetailActivity.class);
                intent.putExtra("url",list.get(position-1).getUrl());
                startActivity(intent);
            }
        });
    }

    private void initListView() {
        listView = ptf.getRefreshableView();
        adapter = new FragNewsItemAdapter(context, list);
        listView.setAdapter(adapter);

        listView.requestDisallowInterceptTouchEvent(true);

    }

    private View initBanner() {
        initBannerData();
        View banner = View.inflate(context, R.layout.layout_banner, null);
        viewPager = (ViewPager) banner.findViewById(R.id.viewpager_banner);
        tv_desc = (TextView) banner.findViewById(R.id.tv_desc);
        tv_ratio = (TextView) banner.findViewById(R.id.tv_ratio);
        ll_dots = (LinearLayout) banner.findViewById(R.id.ll_dots);


        initViewPager();
        initDots();
        tv_desc.setText(topTitleList.get(0));
        tv_ratio.setText(1+"/"+topTitleList.size());
        return banner;
    }

    private void initDots() {
        ll_dots.removeAllViews();
        dotsList.clear();

        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(10, 10);
        for (int i = 0; i < topImagesList.size(); i++) {
            TextView tv = new TextView(context);
            if (i == 0){
                tv.setBackgroundResource(R.mipmap.dot_focus);
            } else{
                tv.setBackgroundResource(R.mipmap.dot_normal);
            }
            params.setMargins(10,0,0,0);
            ll_dots.addView(tv,params);
            dotsList.add(tv);
        }
    }

    private void initBannerData() {
        topTitleList.clear();
        topImagesList.clear();
        for (int i = 0; i < topnewsList.size(); i++) {
            topImagesList.add(topnewsList.get(i).getTopimage());
            topTitleList.add(topnewsList.get(i).getTitle());
        }
    }

    private void initViewPager() {
        FragNewsItemViewPager pagerAdaper = new FragNewsItemViewPager(topImagesList);
        viewPager.setAdapter(pagerAdaper);
        viewPager.setCurrentItem(topImagesList.size()*1000);

        //setOnPageChangeListener  addOnPageChangeListener
        viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                tv_desc.setText(topTitleList.get(position));
                tv_ratio.setText(1 + position + "/" + topTitleList.size());
                for (int i = 0; i < dotsList.size(); i++) {
                    if (position == i){
                        dotsList.get(i).setBackgroundResource(R.mipmap.dot_focus);
                    } else{
                        dotsList.get(i).setBackgroundResource(R.mipmap.dot_normal);
                    }
                }
                LogUtil.d(TAG,"position="+position+"--"+topTitleList.get(position));
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    private void initPtf() {
        ptf = (PullToRefreshListView) rootView.findViewById(R.id.pull_refresh_list);
        ptf.setMode(PullToRefreshBase.Mode.BOTH);
        ptf.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {
            @Override
            public void onRefresh(final PullToRefreshBase<ListView> refreshView) {
                if (refreshView.getCurrentMode() == PullToRefreshBase.Mode.PULL_FROM_START) {//下拉
                    new Handler().post(new Runnable() {
                        @Override
                        public void run() {
                            refreshView.onRefreshComplete();
                        }
                    });
                } else {
                    requestData(moreUrl);
                }
            }
        });
    }


    private void requestData(String url) {
        if (!TextUtils.isEmpty(url)) {
            MainRequest.getInstance().makePostRequest(NetUrl.BASE_URL + url, null, new RequestCallBack<String>() {
                @Override
                public void onSuccess(ResponseInfo<String> responseInfo) {
//                    LogUtil.d(TAG, "responseInfo=" + responseInfo.result);
                    FragNewsItemBean bean = GsonUtil.jsonToBean(responseInfo.result, FragNewsItemBean.class);
                    moreUrl = bean.getData().getMore();
                    topnewsList = bean.getData().getTopnews();
                    list.addAll(bean.getData().getNews());
                    adapter.notifyDataSetChanged();
                    ptf.onRefreshComplete();

                    //添加轮播图
                    View banner = initBanner();
                    listView.addHeaderView(banner);
                }

                @Override
                public void onFailure(HttpException error, String msg) {
//                    LogUtil.d(TAG, "error=" + error.toString());
                }
            });
        } else {
            new Handler().post(new Runnable() {
                @Override
                public void run() {
                    ToastUtil.showShortToast(context, "没有数据了");
                    ptf.onRefreshComplete();
                }
            });
        }
    }
}
